<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ include file="/common/common.jsp" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>商品添加</title>
	<link href="${ctx}/static/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
    <link href="${ctx}/static/css/basic.css" rel="stylesheet" type="text/css">
    <link href="${ctx}/static/plugins/layer/skin/default/layer.css" rel="stylesheet" type="text/css"/>
    <link href="${ctx}/static/plugins/validationEngine/css/validationEngine.jquery.css" rel="stylesheet" type="text/css">
    <link href="${ctx}/static/dist/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="${ctx}/static/plugins/zyupload/skins/zyupload-1.0.0.css" type="text/css"/>
    <link rel="stylesheet"  href="${ctx}/static/plugins/kindeditor-4.1.7/themes/default/default.css"  type="text/css"/>
<!-- "src/main/resources/static/plugins/zyupload/skins/zyupload-1.0.0.css" -->
     <style type="text/css">
          .red{color: red;}
        .head_title_margin{  margin: 40px;  }
        .head_title{color: #00afd6;font-size: 24px}
        .fa-2 {
            font-size: 2em;
        }
        #addInput i:hover{
            color: blue;
        }
 		select{
        	width: 200px;
        	line-height: 33px;
        	height: 33px;
        }
    </style>
</head>
<body>
<div class="content text-center"  >
    <form class="form-horizontal"       id="operateForm">
        <div class="head_title_margin"><span class="head_title"><strong>基本信息</strong></span><hr></div>
        <div class="form-group">
            <label for="" class="col-sm-1 control-label"><span class="red">*</span>供应商:</label>
            <div class="col-sm-3">
                <select  id="supplierId" name="supplierId"  class="form-control">
	                	<c:forEach var="item" varStatus="status" items="${supplierList}">
	                    	<option value="${item.id }">${item.supplierName}</option>
	                    </c:forEach>
                </select>
                </select>
            </div>
            <label for="" class="col-sm-1 control-label"><span class="red">*</span>商品名称:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[required]"  name="productName" id="productName" value=""
                       placeholder="请输入商品名称" />
            </div>
            <label for="" class="col-sm-1 control-label">商品条形码:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control"  name="barCode" id="barCode" value=""
                       placeholder="商品条形码可以为空" />
            </div>
        </div>

        <div class="form-group">
            <label for="" class="col-sm-1 control-label"><span class="red">*</span>商品数量:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[required, custom[integer], min[1]]"  name="productCount" id="productCount" value=""
                       placeholder="请输入商品数量" />
            </div>
            <label for="" class="col-sm-1 control-label">市场参考价:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[custom[number], min[0]]"   value=""  name="referencePrice" id="referencePrice" value=""
                       placeholder="市场参考价可以为空" />
            </div>
            <label for="" class="col-sm-1 control-label"><span class="red">*</span>零售价:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[required,custom[number], min[0]]"  onblur="setPurchasePrice()"  name="retailPrice" id="retailPrice" value=""
                       placeholder="请输入零售价" />
            </div>
        </div>

        <div class="form-group">
            <label for="" class="col-sm-1 control-label"><span class="red">*</span>进货价:</label>
            <div class="col-sm-3">
                <input type="text"  readonly="readonly" class="form-control validate[required,custom[number], min[0]]"  name="purchasePrice" id="purchasePrice" value=""
                       placeholder="请输入进货价" />
            </div>
            <label for="" class="col-sm-1 control-label"><span class="red">*</span>结算价:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[required,custom[number], min[0]]"  name="settlementPrice" id="settlementPrice" value=""
                       placeholder="请输入结算价" />
            </div>
            <label for="" class="col-sm-1 control-label"><span class="red">*</span>市级起批数量:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[required, custom[integer], min[1]]"  name="municipalBatchQuantity" id="municipalBatchQuantity" value=""
                       placeholder="请输入市级起批数量" />
            </div>
        </div>

        <div class="form-group">
            <label for="" class="col-sm-1 control-label"><span class="red">*</span>商户起批数量:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[required, custom[integer], min[1]]" name="sellerbAtchQuantity" id="sellerbAtchQuantity" value=""
                       placeholder="请输入商户起批数量" />
            </div>
            <label for="" class="col-sm-1 control-label">起售数量:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[custom[integer], min[1]]"  name="saleQuantity" id="saleQuantity" value=""
                       placeholder="起售数量可以为空" />
            </div>
            <label for="" class="col-sm-1 control-label">物流费用:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[custom[number], min[0]]"      name="freight" id="freight" value=""
                       placeholder="物流费用可以为空" />
            </div>
        </div>
             <div class="form-group">
            <label for="" class="col-sm-1 control-label">包邮数量:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[custom[number], min[0]]"      name="numberOfPackages" id="numberOfPackages" value=""
                       placeholder="包邮数量可以为空" />
            </div>
        </div>
        <div class="head_title_margin"><span class="head_title"><strong>详细描述</strong></span><hr></h1></div>
        <div>
            <div class="form-group">
                <label for="" class="col-sm-1 control-label">详细描述:</label>
                <!-- 需要使用富文本 -->
                <div class="col-sm-11">
                <textarea class="form-control"  id="textarea" name="textarea"></textarea>
                </div>
            </div>
        </div>
         <div class="head_title_margin"><span class="head_title"><strong>商品相册</strong></span><hr></div>
        <div class="form-group"><!-- 新上传 -->
            	<p>请上传商品的照片，照片大小不能超过5M，图片总数不能超过5张。</p>
            	<div id="zyupload" class="zyupload"></div> 
        </div>
       
        <div class="form-group">
            <label class="col-sm-1 control-label">商品相册：</label>
            <div class="col-sm-11">
                 	 <div id="zyupload" class="zyupload" ></div>  
            </div>
        </div>
        <div class="head_title_margin"><span class="head_title"><strong>商品属性值</strong></span><hr></div>
        <div class="form-group">
			<label for="" class="col-sm-1 control-label"><span style="color: red">*</span>商品分类:</label>
            <div class="col-sm-3">
                <select id="first"   class="validate[required]"  onchange="getClass(this.options[this.selectedIndex].value,'second');">
                	<option value="" selected="selected">请选择分类</option>
                	<c:forEach var="item" varStatus="status" items="${list}">
                   		<option value="${item.id }">${item.classifyName}</option>
                    </c:forEach>
                </select>
            </div>
            <div class="col-sm-3">
                <select id="second"   class="validate[required]"  onchange="getClass(this.options[this.selectedIndex].value,'three');" >
               	 <option value="" selected="selected">请选择分类</option>
               	 <c:forEach var="item" varStatus="status" items="${list2}">
                   	 <option value="${item.id }">${item.classifyName}</option>
                    </c:forEach>
                </select>
            </div>
            <div class="col-sm-3">
                <select id="three"   class="validate[required]"  onchange="gerProperties()" clas="validate[required,custom[number], min[1]]">
               	 <option value="" selected="selected">请选择分类</option>
                </select>
            </div>
        </div>
        </div>
        <!-- 属性值 -->
        <div id="all">
         </div>
          </div> 
            <div class="form-group">
	            <div class="col-sm-12  text-center">
	                <button type="button" onclick="save();" class="btn btn-primary btn-10">保存</button>
	                <button type="button"  onclick="history.go(-1);" class="btn btn-primary btn-10">返回</button>
	            </div>
	        </div>
        
    </div>
    <input type="hidden" id="levleHidden" value=""/>
    <input type="hidden" id="productPropertyValJSON"  name="productPropertyValJSON" value=""/>
    <input type="hidden" id="imageJSON"  name="imageJSON" value=""/>
    <input type="hidden" id="productClassifyId"  name="productClassifyId" value=""/>
     <input  id="description" name="description" value=""   type="hidden" />
     		<div id="imgHidden">
     				
     		</div>
    </form>
  	<script charset="utf-8" src="${ctx}/static/plugins/kindeditor-4.1.7/kindeditor.js"></script>
<script src="${ctx}/static/plugins/jQuery/jQuery-2.1.4.min.js"></script>
<script src="${ctx}/static/bootstrap/js/bootstrap.min.js"></script>
<script src="${ctx}/static/plugins/layer/layer.js"></script>
<script src="${ctx}/static/plugins/validationEngine/jquery.validationEngine-zh_CN.js"></script>
<script src="${ctx}/static/plugins/validationEngine/jquery.validationEngine.js"></script>
<script src="${ctx}/static/js/common/base.js" type="text/javascript"></script>
<script src="${ctx}/static/js/common/page.js" type="text/javascript"></script>
<script type="text/javascript" src="${ctx}/static/plugins/zyupload/zyupload-1.0.0.js"></script>
	<script charset="utf-8" src="${ctx}/static/plugins/kindeditor-4.1.7/lang/zh_CN.js"></script>
<%-- <script type="text/javascript" src="${ctx}/static//plugins/ckeditor/config.js"></script> --%>
<script type="text/javascript">
var editor;
/*添加删除属性表单*/
$(function () {
	var supplierId="${supplierId}";
	if(supplierId!=""){
		$("#supplierId").val(supplierId);
	}
	
    $(".addppvInput").click(function (e) {
    	var group = $(e.target).parent().parent();
    	var ide =$(e.target).parent().attr("ide");
        var i= group.find("div[ref='add']").length;
        $(this).before('<div  ref="add" class="col-sm-1"><input type="text" ide="' + ide + '" name="content" class="form-control pvcontent p_' + ide + '"' + 
            ' placeholder=""><span onclick="deleteDiv(this)" class="fa fa-minus"></span></div>');
	});
		   
 // 初始化插件
	$("#zyupload").zyUpload({
		width            :   "1000px",                 // 宽度
		height           :   "400px",                 // 高度
		itemWidth        :   "140px",                 // 文件项的宽度
		itemHeight       :   "115px",                 // 文件项的高度
		url              :   "${ctx}/api/attachment/uploadProductImage?module=product", 
		fileType         :   ["jpg","png","gif","bmp","jpeg"],// 上传文件的类型
		fileSize         :    5242880,               // 上传文件的大小
		multiple         :   true,                    // 是否可以多个文件上传
		dragDrop         :   false,                    // 是否可以拖动上传文件
		tailor           : true,                    // 是否可以裁剪图片
		del              :   true,                    // 是否可以删除文件
		finishDel        :   false,  				  // 是否在上传文件完成后删除预览
		/* 外部获得的回调接口 */
		onSelect: function(selectFiles, allFiles){    // 选择文件的回调方法  selectFile:当前选中的文件  allFiles:还没上传的全部文件
// 			console.info("当前选择了以下文件：");
// 			console.info(selectFiles);  返回一个数组
		},
		onDelete: function(file, files){              // 删除一个文件的回调方法 file:当前删除的文件  files:删除之后的文件
			$("#img" + file.index).remove();
			console.info("当前删除了此文件：");
			console.info(file.name);
		},
		onSuccess: function(file, response){          // 文件上传成功的回调方法
// 			console.info("此文件上传成功：");
// 			console.info(file.name);
// 			console.info(file);
// 			console.info("此文件上传到服务器地址：");
			console.info(response);
			var rs = JSON.parse(response);
			$("#imgHidden").append('<input type="hidden" name="imageInput" id="img'+ file.index +'" class="hImag" value="'+ rs.data +'"/>');
// 			$("#uploadInf").append("<p>上传成功，文件地址是：" + response + "</p>");
		},
		onFailure: function(file, response){          // 文件上传失败的回调方法
			console.info("此文件上传失败：");
			console.info(file.name);
		},
		onComplete: function(response){           	  // 上传完成的回调方法
			console.info("文件上传完成");
			console.info(response);
		}
	});
    
    


 $("#operateForm").validationEngine({ 
		promptPosition: "topRight", 
		validationEventTriggers:"keyup blur", 
		success :  false,
		failure : function() { callFailFunction()  }
	});
		//富文本编辑器初始化
 KindEditor.ready(function(K) {
     editor= K.create('#textarea',{
    	   	    uploadJson : '${ctx}/uploadProductImage?module=editor',
    	 		allowFileManager : false,
    	 		allowFlashUpload:false,
    	 		allowMediaUpload:false,
    	 		formatUploadUrl:false,  
    	 		items:[
    	 		        'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'cut', 'copy', 'paste',
    	 		        'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
    	 		        'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
    	 		        'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
    	 		        'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
    	 		        'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image',
    	 		        'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
    	 		        'anchor', 'link', 'unlink', '|', 'about'
    	 		],
     	});
			
});

});

function deleteDiv(sp){
     $(sp).parent().remove();
}
 
        
function getClass(id,level){
	$("#levleHidden").val("");
	$("#levleHidden").val(level);
	if(id!=""){
	$.ajax({url:'${ctx}/api/productClassify/selectClass?id='+id,dataType:"json",type:"post",success:savecallbackOne,error:function(data){
				layer.alert("与服务器连接中断");
 }});
	}
}
 function savecallbackOne(data){
	var levle=$("#levleHidden").val();
	if(levle=="second"){
		$("#three").find("option").remove();
		$("#three").prepend("<option value=''>请选择分类</option>");
	}
	$("#"+levle).find("option").remove();
	$("#"+levle).prepend("<option value=''>请选择分类</option>");
	for(var i=0; i<data.data.length;i++){
              $("#"+levle).append("<option value='"+data.data[i].id+"'>"+data.data[i].classifyName+"</option>");
          }
}
 
//保存方法
	function save(){
		var content=editor.html();
	   	if(content!=null&&content!=""){
	   		$("#description").val(content);
	   	}
		//表单验证
	 	var flag = $("#operateForm").validationEngine("validate");
    	if(!flag){
     		return false;
    	} 
    	if($("#imgHidden").find("input").length==0){
    		layer.msg('请上传商品图片', {
				  icon: 1,
				  time: 1000 //2秒关闭（如果不配置，默认是3秒）
				});
    		return  false;
    	}
    	if($("#imgHidden").find("input").length>5){
    		layer.msg('最多只可以上传五张图片', {
				  icon: 1,
				  time: 1000 //2秒关闭（如果不配置，默认是3秒）
				});
    		return  false;
    	}
    	
    	$("#productClassifyId").val($("#three").val());
    	//组装属性值
    	var productPropertyValJSON = [];
    	$(".pvcontent").each(function(){
    		if(null != $(this).val() && "" != $.trim($(this).val()) ){
    			var obj = new Object();
    			obj.propertyId = $(this).attr("ide");
    			obj.content = $.trim($(this).val());
    			productPropertyValJSON.push(obj);
    		}
    	  });
    	$("#productPropertyValJSON").val(JSON.stringify(productPropertyValJSON));
    	
    	//组装图片 测试数据
    	var imageJSON = [];
    	$("#imgHidden").find("input").each(function(index){
    		if(null != $(this).val() && "" != $.trim($(this).val()) ){
    			var obj = new Object();
    			obj.url = $(this).val();
    			obj.sort = index+1
    			imageJSON.push(obj);
    		}
    	  });
    	$("#imageJSON").val(JSON.stringify(imageJSON));
    	
//     	var imageJSON = [{url: "http://pic8.58cdn.com.cn/bidding/big/n_v1bl2lwkpnpqqvohmq4mca_8024e0290b13ddc6.png?w=800&h=600",sort: 1},
//     				     {url: "http://pic5.58cdn.com.cn/bidding/big/n_v1bkuyfvjhmj7fnnzjnzqa_5e74747ac852dbb4.png?w=800&h=600",sort: 2}
//     					];
    	 //获取富文本的值	
   		
		 var poststr=$('#operateForm').serialize();
			$.ajax({url:'${ctx}/api/product/add',data :$("#operateForm").serialize(),dataType:"json",type:"post",success:savecallback,error:function(data){
						layer.alert("与服务器连接中断");
	     }});
	}
	//成功回调方法
function savecallback(data){
			if(data.code=="200"){
				resetForm();
				layer.confirm('新增商品成功',{
		            icon: 1,
		            btn: ['继续添加', '返回'],
		            btn1: function(index){
// 		            	layer.close(index);
		            	 window.location.href="${ctx}/api/product/toAddProductPage";
		            },
		            btn2: function(index){
		            	  window.location.href="${ctx}/api/product/listPage";
		            }
		        });
			}else{
			if(data.code=="70004" )
			{  
				layer.msg(data.message, {icon: 2}); 
			}
			if(data.code=="70001" )
			{  
				layer.msg(data.message, {icon: 2}); 
			}
			}
		}
	
function  resetForm(){
	$('#operateForm').find("input").val("");
	$('#operateForm').find("select").val("");
	$("#description").html("");
	$("#all").html("");
	$("#imgHidden").html("");
}
	
function gerProperties(){
			var fid=$("#first").val();
			var sid=$("#second").val();
			var tid=$("#three").val();
			if(fid==""||sid==""||tid==""){
				layer.alert("请选择分类");
				return false;
			}
			if(tid!=""){
				$.ajax({url:'${ctx}/api/product/getClassifiesForThreeId?fid='+fid+'&sid='+sid+'&tid='+tid,dataType:"json",type:"get",success:savecallbackForSelect,error:function(data){
						layer.alert("与服务器连接中断");
	    		 }});
			}
}
//成功回调方法
function savecallbackForSelect(data){
			$("#all").html("");
		var html="";
		for(var i=0; i<data.data.length;i++){
			html+="<div class='form-group col-sm-12 ppvDiv'  ide="+data.data[i].id+" classifyId="+data.data[i].classifyId+">";
			html+="<label for='' class='col-sm-1 control-label'>"+data.data[i].propertyName +"</label>";
			html+=" <div class='col-sm-1'>";
			html+="<input type='text' class='form-control pvcontent p_${property.id}'  ide="+data.data[i].id+" name='content'  value='' placeholder='' /><span onclick='deleteDiv(this)' class='fa fa-minus'></span>";
			html+="</div>";
			html+="<span class='col-sm-1 addppvInput' ide="+data.data[i].id+" ><i class='fa fa-plus fa-2' aria-hidden='true'></i></span>";
			html+="</div>";
        }
		$("#all").append(html);
		 $(".addppvInput").click(function (e) {
		    	var group = $(e.target).parent().parent();
		    	var ide =$(e.target).parent().attr("ide");
		        var i= group.find("div[ref='add']").length;
		        $(this).before('<div  ref="add" class="col-sm-1"><input type="text" ide="' + ide + '" name="content" class="form-control pvcontent p_' + ide + '"' + 
		            ' placeholder=""><span onclick="deleteDiv(this)" class="fa fa-minus"></span></div>');
			});
	}
	
//设置进货价
function setPurchasePrice(){
	var retailPrice = $("#retailPrice").val();
	var purchasePrice = (retailPrice * 0.61).toFixed(2);
	$("#purchasePrice").val(purchasePrice);
}
//  	function back(){
//  		  window.location.href="${ctx}/static/api/product/listPage";
//  	}
</script>
</body>
</html>